package com.example.webmodule.config.strategy;

import com.example.webmodule.strategy.EurekaRegistryStrategy;
import com.example.webmodule.strategy.RegistrySelectStrategy;
import com.example.webmodule.strategy.RegistryStrategyFactory;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnProperty(name = "eureka.client.enabled", havingValue ="true", matchIfMissing = false)
@ConditionalOnClass(EurekaClientConfigBean.class)
@Configuration
public class EurekaRegistryStrategyConfig {

    private static final Logger logger = LoggerFactory.getLogger(EurekaRegistryStrategyConfig.class);

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private OkHttpClient okHttpClient;

    @Bean(value="eurekaRegistryStrategy")
    public RegistrySelectStrategy eurekaRegistryStrategy() {
        if (discoveryClient == null) {
            logger.error("DiscoveryClient is not properly injected, EurekaRegistryStrategy cannot be initialized.");
            throw new IllegalStateException("DiscoveryClient is required for EurekaRegistryStrategy initialization.");
        }
        return new EurekaRegistryStrategy(discoveryClient, okHttpClient);
    }

    @Bean
    public RegistryStrategyFactory registryStrategyFactory(
            @Qualifier("eurekaRegistryStrategy") RegistrySelectStrategy registrySelectStrategy) {
        if (registrySelectStrategy == null) {
            logger.error("RegistrySelectStrategy is null, RegistryStrategyFactory cannot be initialized.");
            throw new IllegalArgumentException("RegistrySelectStrategy must not be null.");
        }
        logger.info("Initializing RegistryStrategyFactory with provided RegistrySelectStrategy.");

        RegistryStrategyFactory registryStrategyFactory = RegistryStrategyFactory.instance;
        registryStrategyFactory.setRegistryStrategy(registrySelectStrategy);
        return registryStrategyFactory;
    }
}
